package applogic

import (
	"encoding/json"
	"fmt"

	"github.com/gin-gonic/gin"
)

func DownloadFile(c *gin.Context) {
	var jsondata struct {
		Name    string `json:"名称"`
		SelList []struct {
			FileName string `json:"文件名"`
			M3Url    string `json:"下载连接"`
		} `json:"选集"`
	}
	data, _ := c.GetRawData()
	err := json.Unmarshal(data, &jsondata)
	if err != nil {
		c.JSON(200, gin.H{"err": err, "playerlist": nil})
		return
	}
	for _, m := range jsondata.SelList {
		filename := m.FileName
		m3url := m.M3Url
		go func(Name, filename, m3url string) {
			AppWsConn.Mux.Lock()
			defer AppWsConn.Mux.Unlock()
			// todo------
			err := AppWsConn.WriteJSON(gin.H{"下载": Name})
			if err != nil {
				c.JSON(200, gin.H{"err": err})
				return
			}
		}(jsondata.Name, filename, m3url)

	}
	defer func() {
		if r := recover(); r != nil {
			c.JSON(200, gin.H{"err": err})
		}
	}()

	c.JSON(200, gin.H{"msg": fmt.Sprintf("正在下载%s -> %s", jsondata.Name, jsondata.SelList)})
}
